package com.atguigu.day01;


import com.sunfeng.TimeUtils;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author : 孙峰
 * @Description:
 * @Date : 2022/6/28  11:00
 */
public class CompletableFutureMallDemo {
    static List<NetMall> list = Arrays.asList(
            new NetMall("jd"),
            new NetMall("dangdang"),
            new NetMall("taobao"),
            new NetMall("pdd"),
            new NetMall("tmall")
    );

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        getPriceByCompletableFuture("aaaaaaa");
        long endTime = System.currentTimeMillis();
        System.out.println("花费的时间为：" + (endTime - startTime));
    }

    private static List<String> getPriceByCompletableFuture(String productName) {

        List<String> collect = list.stream()
                .map(netMall -> CompletableFuture
                        .supplyAsync(() ->
                                String.format(productName + "in %s price is %.2f", netMall.getNetMallName(), netMall.calcPrice(productName))))
                .collect(Collectors.toList())
                .stream()
                .map(CompletableFuture::join)
                .collect(Collectors.toList());

        return collect;

    }

    private static List<String> getPriceByCommon(String productName) {

        List<String> collect = list.stream().map(netMall -> {
            double v = netMall.calcPrice(productName);
            return String.format("in %s price is %.2f", netMall.getNetMallName(), v);
        }).collect(Collectors.toList());
        return collect;
    }

}

@Data
@AllArgsConstructor
class NetMall {
    private String netMallName;

    public double calcPrice(String productName) {
        TimeUtils.sleep(1);
        return ThreadLocalRandom.current().nextDouble() * 2 + productName.charAt(0);
    }
}
